package br.com.leopard.erp.gym.bean.login;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;
import javax.servlet.http.HttpSession;

import br.com.leopard.erp.gym.login.LoginException;
import br.com.leopard.erp.gym.login.LoginNegocio;
import br.com.leopard.erp.gym.session.UsuarioSession;
import br.com.leopard.erp.gym.web.session.UsuarioNavegacaoSession;
import br.com.leopard.erp.gym.web.util.JSFMessageUtil;

@ManagedBean
@SessionScoped
public class LoginBean implements Serializable {

	private static final long serialVersionUID = 1L;

	@Inject
	private LoginNegocio loginNegocio;

	@ManagedProperty(value = "#{usuarioNavegacaoSession}")
	private UsuarioNavegacaoSession navegacaoSession;

	@Inject
	private UsuarioSession sessaoUsuario;

	private String login;

	private String senha;

	@PostConstruct
	private void init() {
	}

	public void logarSistemaActionEvent(ActionEvent event) {
		try {
			loginNegocio.logarComSenhaDescriptografada(login, senha);

			HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
			session.setAttribute("currentUser", sessaoUsuario.getUsuarioLogado());

			navegacaoSession.redirecionarHomePortal();
		} catch (LoginException e) {
			JSFMessageUtil.sendErrorMessageToUser("Login e/ou senha incorretos.");
		}

	}

	public void logoutAcionEvent(ActionEvent event) {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);

		session.removeAttribute("currentUser");
		session.invalidate();

		navegacaoSession.redirecionarPaginaLogin();
	}

	public void limparCampos(ActionEvent event) {
		login = null;
		senha = null;
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getSenha() {
		return senha;
	}

	public void setSenha(String senha) {
		this.senha = senha;
	}

	public void setNavegacaoSession(UsuarioNavegacaoSession navegacaoSession) {
		this.navegacaoSession = navegacaoSession;
	}

}
